﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using WxApi.Comm;
using WxApi.Models;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace WxApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        private readonly string AppId = "wxf70dec5e4822772e";
        private readonly string AppSecret = "588ff43ba039e154ab90643b85353d80";

        [HttpPost]
        [Route("TestWX")]
        public async Task<IActionResult> TestWX([FromBody] WxModel data)
        {
            try
            {
                string code = data.Code;
                var phoneNumber = await GetUserPhoneNumber(code);
                return Ok(new { phoneNumber });
            }
            catch (Exception ex)
            {
                // Handle error
                return StatusCode(500, ex.Message);
            }
        }

        /// <summary>
        /// 调用api获取session_key
        /// </summary>
        /// <returns></returns>
        private async Task<string> GetSession(string code)
        {
            string url = $"https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&appid={AppId}&secret={AppSecret}&js_code={code}";
            var ss = await HttpComm.GetRequest(url);
            return ss;
        }


        /// <summary>
        /// 调用api获取access_token
        /// </summary>
        /// <returns></returns>
        private async Task<string> GetToken()
        {
            string url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={AppId}&secret={AppSecret}";
            var content = await HttpComm.GetRequest(url);
            dynamic result = JObject.Parse(content);
            string access_token = result.access_token;
            return access_token;
        }

        /// <summary>
        /// 获取手机号
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private async Task<string> GetUserPhoneNumber(string code)
        {
            string token = await GetToken();
            string url = $"https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token;
            JObject a = new JObject();
            a.Add("code", code);

            var content = await HttpComm.PostJson(url, a);
            // 解析JSON字符串
            JObject jsonObject = JObject.Parse(content);

            // 获取phoneNumber字段的值
            string phoneNumber = jsonObject.SelectToken("phone_info.phoneNumber").ToString();
            return phoneNumber;
        }
    }
}
